/*
 * VentCreaProd.java
 *
 * Created on 20 de julio de 2006, 11:28
 */

package administrador;
import java.awt.Panel;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*; 
/**
 *
 * @author  CARLOS SILVA
 */
public class VentCreaProd extends javax.swing.JFrame {
Conexion conexion;   
ResultSet r;
Productos p;
KardexInOut k;
int bodega;
String bandera="";


    /** Creates new form VentCreaProd */
    public VentCreaProd(Conexion cEnt,int bEnt,Productos pEnt) {
        initComponents();
        conexion=cEnt;
        bodega=bEnt;
        p=pEnt;
        muestroBodegas(bodega);
        muestroCategorias();
        
        this.setSize(364, 380);
        this.setLocation(200,100);
        this.setVisible(true);
        ponerFecha();
    }
    
    public VentCreaProd(Conexion cEnt,int bEnt,Productos pEnt,String codigo) {
        initComponents();
        conexion=cEnt;
        bodega=bEnt;
        p=pEnt;
        txt_codigo.setText(codigo);
        muestroBodegas(bodega);
        muestroCategorias();
        
        this.setSize(344, 360);
        this.setLocation(200,100);
        this.setVisible(true);
        ponerFecha();
    }
    
    
    /** Creates new form VentCreaProd */
    public VentCreaProd(Conexion cEnt,int bEnt) {
        initComponents();
        conexion=cEnt;
        bodega=bEnt;
        muestroBodegas(bodega);
        muestroCategorias();
        
        this.setSize(344, 360);
        this.setLocation(200,100);
        this.setVisible(true);
        ponerFecha();
    }
    
    public VentCreaProd(Conexion cEnt,int bEnt,KardexInOut kaEnt) {
        initComponents();
        conexion=cEnt;
        bodega=bEnt;
        k=kaEnt;
        muestroBodegas(bodega);
        muestroCategorias();
        
        this.setSize(364, 380);
        this.setLocation(200,100);
        this.setVisible(true);
        bandera="kardexInOut";
        ponerFecha();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txt_codigo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cb_bodegas = new javax.swing.JComboBox();
        cb_categoria = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        area_nom = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txt_precio = new javax.swing.JTextField();
        txt_rank = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txt_min = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        area_desc = new javax.swing.JTextArea();
        jButton4 = new javax.swing.JButton();
        txt_costo = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        lbl_fecha = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txt_distribucion = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Creacion Productos");
        setAlwaysOnTop(true);
        getContentPane().setLayout(null);
        getContentPane().add(txt_codigo);
        txt_codigo.setBounds(90, 70, 130, 20);

        jLabel1.setText("Codigo:");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(20, 70, 60, 20);

        jLabel3.setText("Bodegas");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(20, 40, 80, 20);

        getContentPane().add(cb_bodegas);
        cb_bodegas.setBounds(90, 40, 130, 20);

        getContentPane().add(cb_categoria);
        cb_categoria.setBounds(90, 10, 130, 20);

        jLabel2.setText("Categoria:");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(20, 10, 80, 20);

        jButton1.setText("Crear");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(220, 250, 120, 30);

        jLabel4.setText("Nombre");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(20, 110, 60, 14);

        area_nom.setColumns(20);
        area_nom.setRows(5);
        jScrollPane1.setViewportView(area_nom);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(90, 100, 240, 60);

        jLabel5.setText("Precio Costo:");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(20, 240, 80, 20);

        jLabel6.setText("Ranking");
        getContentPane().add(jLabel6);
        jLabel6.setBounds(20, 280, 80, 20);

        txt_precio.setText("0.00");
        getContentPane().add(txt_precio);
        txt_precio.setBounds(110, 260, 100, 20);

        txt_rank.setText("5");
        getContentPane().add(txt_rank);
        txt_rank.setBounds(110, 280, 100, 20);

        jLabel8.setText("Cant Min");
        getContentPane().add(jLabel8);
        jLabel8.setBounds(20, 300, 80, 20);

        txt_min.setText("5");
        getContentPane().add(txt_min);
        txt_min.setBounds(110, 300, 100, 20);

        jButton2.setText("Limiar Campos");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(220, 280, 120, 20);

        jButton3.setText("Agregar Foto");
        getContentPane().add(jButton3);
        jButton3.setBounds(220, 300, 120, 23);

        jLabel9.setText("Descripcion");
        getContentPane().add(jLabel9);
        jLabel9.setBounds(20, 170, 70, 14);

        area_desc.setColumns(20);
        area_desc.setRows(5);
        jScrollPane2.setViewportView(area_desc);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(90, 170, 240, 60);

        jButton4.setText("Nuevo Codigo");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4);
        jButton4.setBounds(230, 70, 100, 23);

        txt_costo.setText("0.00");
        getContentPane().add(txt_costo);
        txt_costo.setBounds(110, 240, 100, 20);

        jButton5.setText("Precio Venta:");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5);
        jButton5.setBounds(10, 260, 100, 20);

        jLabel10.setText("Fecha Creacion:");
        getContentPane().add(jLabel10);
        jLabel10.setBounds(250, 20, 80, 14);

        lbl_fecha.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbl_fecha.setForeground(new java.awt.Color(0, 102, 102));
        lbl_fecha.setText("2008-02-02");
        getContentPane().add(lbl_fecha);
        lbl_fecha.setBounds(250, 30, 80, 20);

        jLabel7.setText("Distribución");
        getContentPane().add(jLabel7);
        jLabel7.setBounds(20, 320, 60, 14);
        getContentPane().add(txt_distribucion);
        txt_distribucion.setBounds(110, 320, 100, 20);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
  String codigo=txt_codigo.getText();
    System.out.println("El producto es:|"+codigo+"|");
    if(!codigo.equals("")){
    VentCosto vc=new VentCosto(codigo,conexion,this);    
    }else{
         JOptionPane.showMessageDialog(this,"El codigo del producto no es Correcto","Informacion",JOptionPane.INFORMATION_MESSAGE);
    }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
        limpiar();
    }//GEN-LAST:event_jButton2ActionPerformed
 public void limpiar(){
    area_nom.setText("");
    area_desc.setText("");
    txt_precio.setText("0.0");
    txt_rank.setText("5");
    txt_codigo.setText("");
    }
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    
        
// TODO add your handling code here:
//Obtengo la Categoria para el nuevo Codigo
   int categoria=cb_categoria.getSelectedIndex()+1;      


//Obtengo un Nuevo Codigo
    r=conexion.consultarBase("select * from producto where cod_categoria="+categoria+" ;");
    String maximo="";

    try{
        r.last();
        maximo=r.getString(1);
        
        }catch(SQLException sqle){System.err.println(sqle);}
    
    JOptionPane.showMessageDialog(this,"El ultimo codigo para esta Categoria fue: "+maximo,"Informacion",JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_jButton4ActionPerformed
   public void muestroBodegas(int bodega){
     cb_bodegas.removeAllItems();
     ResultSet r=conexion.consultarBase("select * from bodega");
     try{
            int numBodegas=conexion.obtenerFilas(r);
            r.beforeFirst();
            while(r.next()){
            cb_bodegas.addItem(r.getString(1)+" | "+r.getString(2));
            }
        }
       catch(SQLException sqle){
            System.out.println("Error al mostrar Bodegas");
            System.err.println(sqle);
        }

      cb_bodegas.setSelectedIndex(0);
    }
    
      public void muestroCategorias(){
     
     ResultSet r=conexion.consultarBase("select * from categoria");
     try{
            r.beforeFirst();
            
            while(r.next()){
            String catS=r.getString(2);
            cb_categoria.addItem(catS);
            }
            
        }
       catch(SQLException sqle){
            System.out.println("Error al mostrar Bodegas");
            System.err.println(sqle);
        }
     
     
    }
      
      
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//Valido los Campos
        if(txt_codigo.getText().equals("") || area_nom.getText().equals("") || txt_precio.getText().equals("") ||txt_costo.getText().equals("") || txt_rank.getText().equals("") || txt_distribucion.getText().equals("")){
            JOptionPane.showMessageDialog(this,"Falta llenar campos del Producto","Informacion",JOptionPane.INFORMATION_MESSAGE);
        } else{
            
            try{
                Double precio=Double.valueOf(txt_precio.getText());
                int cant=0;
                int rank=Integer.parseInt(txt_rank.getText());
                
                if(precio.intValue()>=0 && cant>=0 && rank>=0){
                    if(rank<=5){
                        
                        //Saco Categoria
                        int categoria=cb_categoria.getSelectedIndex()+1;
                        //Saco Bodegas:
                        int bodegaIn=Integer.valueOf(cb_bodegas.getSelectedItem().toString().split(" ")[0]);
                        
                        String nombre=area_nom.getText();
                        nombre=nombre.replaceAll("'"," ");
                        String descripcion=area_desc.getText();
                        descripcion=descripcion.replaceAll("'"," ");
                        String codigoP=txt_codigo.getText();
                        codigoP=codigoP.replaceAll(" ","");
                        
                        //Realizo la Insercion de Producto Nuevo.
                        
                        r=conexion.consultarBase("select * from producto where cod_producto like '"+codigoP+"'");
                        int fila_num=conexion.obtenerFilas(r);
                        if(fila_num>0){
                            JOptionPane.showMessageDialog(this,"El codigo ya Existe no Creo Producto","Informacion",JOptionPane.INFORMATION_MESSAGE);
                        } else{
                            //Inserto Nuevo Productos:
                            conexion.insertarDatos("insert into producto values('"+codigoP+"',"+categoria+",'"+nombre+"','"+descripcion+"',"+cant+","+txt_precio.getText()+","+txt_rank.getText()+","+txt_costo.getText()+",'"+lbl_fecha.getText()+"',"+txt_distribucion.getText()+")");
                            //Inserto Nuevo Detalle de Bodega:
                            conexion.insertarDatos("insert into itm_bodega values("+bodegaIn+",'"+codigoP+"',0,"+txt_min.getText()+")");
                            
                            //Creo Producto en Inventario:
                            try {
                            ResultSet rinv=conexion.consultarBase("SELECT * FROM inventario where abierto=true;");
                            int filnum=conexion.obtenerFilas(rinv);
                                if(filnum>0){
                                    int codigoInv = rinv.getInt(1);
                                    //Creo el producto en el inventario Abierto:
                                    conexion.insertarDatos("insert into productoinv values("+codigoInv+",'"+codigoP+"','"+categoria+"','"+nombre+"','"+descripcion+"',"+txt_costo.getText()+","+txt_precio.getText()+","+cant+",0,"+txt_distribucion.getText()+",'"+lbl_fecha.getText()+"')");

                                }
                            } catch (SQLException ex) {
                                Logger.getLogger(VentCreaProd.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            //+++++++++++++++++++++++++++:
                            
                            JOptionPane.showMessageDialog(this,"Producto Codigo:"+codigoP+" con el nombre: "+nombre+" fue Creado con EXITO","Informacion",JOptionPane.INFORMATION_MESSAGE);
                            
                            //Pongo segun la Ventana:
                            //Caso que sea la ventana de Kardex
                            if(bandera.equals("kardexInOut")){
                            int filaDesocupada=k.cuentaFilaOcupadas();

                             if(k.Etiqueta.getText().equals("Factura de Compras")){
                             k.tabla.setValueAt(this.txt_codigo.getText(),filaDesocupada,0);
                             this.dispose();   
                             }
                            if(k.Etiqueta.getText().equals("Ventas X Mayor"))
                             {
                                k.tabla.setValueAt(this.txt_codigo.getText(),filaDesocupada,0);
                                
//                             if(cantidadProd>0){
//                                filaDesocupada=kardexPrin.cuentaFilaOcupadas();
//                                kardexPrin.tabla.setValueAt(tabla.getValueAt(tabla.getSelectedRow(),0),filaDesocupada,0);
//                                }else{
//                                JOptionPane.showMessageDialog(this,"No existe este Producto en Stock","Informacion",JOptionPane.INFORMATION_MESSAGE);
//                                }
                             }
                            
                            }
                            
                        }
                        
                        if(p!=null){
                        p.txt_codigo.setText(codigoP);
                        p.muestraProducto();}
                        
                        
                        
                    } else{
                        JOptionPane.showMessageDialog(this,"Ranking debe ser del 1-5","Informacion",JOptionPane.INFORMATION_MESSAGE);
                    }
                    
                } else{
                    JOptionPane.showMessageDialog(this,"Valores negativos o nulos","Informacion",JOptionPane.INFORMATION_MESSAGE);
                }
            }catch(java.lang.NumberFormatException e){
                JOptionPane.showMessageDialog(this,"Hay un error en el Formato","Informacion",JOptionPane.INFORMATION_MESSAGE);
            }
            
            
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    public void ponerFecha(){
    String fecha=new java.sql.Date(System.currentTimeMillis()).toString();
    lbl_fecha.setText(fecha);
    }
  
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea area_desc;
    private javax.swing.JTextArea area_nom;
    private javax.swing.JComboBox cb_bodegas;
    private javax.swing.JComboBox cb_categoria;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbl_fecha;
    private javax.swing.JTextField txt_codigo;
    public javax.swing.JTextField txt_costo;
    private javax.swing.JTextField txt_distribucion;
    private javax.swing.JTextField txt_min;
    public javax.swing.JTextField txt_precio;
    private javax.swing.JTextField txt_rank;
    // End of variables declaration//GEN-END:variables
    
}
